// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    
    // 关于我们下拉菜单显示/隐藏逻辑
    const aboutUsBtn = document.getElementById('aboutUsBtn');
    const aboutUsDropdown = document.getElementById('aboutUsDropdown');
    
    if (aboutUsBtn && aboutUsDropdown) {
        aboutUsBtn.addEventListener('click', function(e) {
            e.preventDefault();
            aboutUsDropdown.classList.toggle('show');
        });
        
        // 点击其他区域关闭下拉菜单
        document.addEventListener('click', function(e) {
            if (aboutUsBtn && aboutUsDropdown && !aboutUsBtn.contains(e.target) && !aboutUsDropdown.contains(e.target)) {
                aboutUsDropdown.classList.remove('show');
            }
        });
        
        // 为下拉菜单中的荣誉证书和合作伙伴按钮添加点击事件
        const dropdownItems = document.querySelectorAll('#aboutUsDropdown .dropdown-item');
        dropdownItems.forEach(item => {
            item.addEventListener('click', function() {
                // 确保点击后能正常跳转到相应页面
                if (this.textContent.trim() === '合作伙伴') {
                    this.setAttribute('href', 'certificates.html?type=partners');
                } else if (this.textContent.trim() === '荣誉证书') {
                    this.setAttribute('href', 'certificates.html?type=certificates');
                }
            });
        });
    }
    


    // 初始化轮播
    const bannerCarousel = new bootstrap.Carousel(document.getElementById('bannerCarousel'), {    
        interval: 5000, // 5秒自动切换
        pause: 'hover', // 鼠标悬停时暂停
        wrap: true, // 循环播放
        touch: true // 支持触摸滑动
    });

    // 初始化荣誉证书轮播并实现倒转功能
    const certificatesCarousel = new bootstrap.Carousel(document.getElementById('certificatesCarousel'), {
        interval: 3000, // 3秒自动切换（与CSS中保持一致）
        pause: 'hover',
        wrap: false, // 关闭默认的循环，因为我们要实现自定义的倒转逻辑
        touch: true
    });

    // 获取所有轮播项
    const carouselItems = document.querySelectorAll('#certificatesCarousel .carousel-item');
    let isForward = true; // 标记当前轮播方向
    let currentIndex = 0;
    const totalItems = carouselItems.length;

    // 自定义轮播控制函数，实现12345 54321的倒转逻辑
    function startCustomCarousel() {
        setInterval(() => {
            // 检查是否达到边界需要改变方向
            if (isForward && currentIndex === totalItems - 1) {
                isForward = false;
            } else if (!isForward && currentIndex === 0) {
                isForward = true;
            }

            // 根据方向切换到上一张或下一张
            if (isForward) {
                certificatesCarousel.next();
                currentIndex++;
            } else {
                certificatesCarousel.prev();
                currentIndex--;
            }
        }, 3000); // 与CSS中的自动轮播间隔保持一致
    }

    // 监听轮播滑动事件，更新当前索引
    const certificatesCarouselEl = document.getElementById('certificatesCarousel');
    if (certificatesCarouselEl) {
        certificatesCarouselEl.addEventListener('slid.bs.carousel', function() {
            // 找到当前活动的轮播项
            carouselItems.forEach((item, index) => {
                if (item.classList.contains('active')) {
                    currentIndex = index;
                }
            });
        });

        // 启动自定义轮播
        startCustomCarousel();
    }

    // 处理导航栏滚动效果
    window.addEventListener('scroll', function() {
        const navbar = document.querySelector('.navbar');
        if (window.scrollY > 50) {
            navbar.classList.add('bg-white', 'shadow-md');
            navbar.classList.remove('bg-transparent');
        } else {
            navbar.classList.add('bg-white');
            navbar.classList.remove('shadow-md', 'bg-transparent');
        }
    });

    // 移动端导航菜单关闭处理
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', function() {
            const navbarCollapse = document.getElementById('navbarNav');
            if (navbarCollapse.classList.contains('show')) {
                const navbarToggler = document.querySelector('.navbar-toggler');
                navbarToggler.click();
            }
        });
    });

    // 为服务项目添加动画效果
    const serviceItems = document.querySelectorAll('.service-item');
    serviceItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateY(20px)';
        item.style.transition = `opacity 0.5s ease, transform 0.5s ease`;
        
        // 延迟显示每个项目，创建错开效果
        setTimeout(() => {
            item.style.opacity = '1';
            item.style.transform = 'translateY(0)';
        }, 100 * index);
    });

    // 为成绩数字添加计数动画
    const animateNumbers = function() {
        const achievementNumbers = document.querySelectorAll('.achievement-number');
        
        achievementNumbers.forEach(number => {
            const target = parseInt(number.textContent);
            let count = 0;
            const duration = 2000; // 动画持续时间
            const increment = target / (duration / 16);
            
            const updateCount = function() {
                count += increment;
                if (count < target) {
                    number.textContent = Math.floor(count) + (number.textContent.includes('+') ? '+' : (number.textContent.includes('%') ? '%' : ''));
                    requestAnimationFrame(updateCount);
                } else {
                    number.textContent = target + (number.textContent.includes('+') ? '+' : (number.textContent.includes('%') ? '%' : ''));
                }
            };
            
            updateCount();
        });
    };

    // 检测元素是否在视口中
    const isInViewport = function(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.bottom >= 0
        );
    };

    // 当滚动到成绩区域时触发计数动画
    let animated = false;
    window.addEventListener('scroll', function() {
        const achievementsSection = document.getElementById('achievements');
        if (achievementsSection && isInViewport(achievementsSection) && !animated) {
            animateNumbers();
            animated = true;
        }
    });

    // 为荣誉证书添加悬停效果
    const certificateItems = document.querySelectorAll('.certificate-item');
    certificateItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
            this.style.transform = 'scale(1.03) translateY(-8px)';
        });
        
        item.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1) translateY(0)';
        });
    });

    // 为按钮添加点击波纹效果
    const buttons = document.querySelectorAll('button, .btn');
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            const ripple = document.createElement('span');
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            ripple.style.width = ripple.style.height = Math.max(this.offsetWidth, this.offsetHeight) + 'px';
            ripple.style.left = x - ripple.offsetWidth / 2 + 'px';
            ripple.style.top = y - ripple.offsetHeight / 2 + 'px';
            ripple.classList.add('ripple');
            
            const rippleOld = this.querySelector('.ripple');
            if (rippleOld) {
                rippleOld.remove();
            }
            
            this.appendChild(ripple);
        });
    });

    // 图片加载性能优化 - 实现真正的懒加载
    
    // 1. 只为固定的几个图片转换为懒加载模式
    const convertToLazyLoad = () => {
        // 标记：只为有特定标识的图片添加lazy-image类
        // 选择器说明：
        // 1. .lazy-load-marked 类的图片
        // 2. data-lazy="true" 属性的图片
        // 3. 特定区域内的图片（如证书展示区）
        const lazyImages = document.querySelectorAll('img.lazy-load-marked, img[data-lazy="true"], .certificates-carousel img, .lazy-images-container img');
        
        lazyImages.forEach(img => {
            // 保存原始src
            const originalSrc = img.getAttribute('src');
            
            // 设置占位符
            img.setAttribute('data-src', originalSrc);
            img.setAttribute('src', 'data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 viewBox%3D%220 0 1 1%22%3E%3C%2Fsvg%3E');
            
            // 添加样式类
            img.classList.add('lazy-image');
        });
    };
    
    // 2. 实现真正的图片懒加载
    const lazyLoadImages = () => {
        const lazyImages = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    const src = img.getAttribute('data-src');
                    
                    // 创建新图片对象预加载
                    const tempImg = new Image();
                    tempImg.onload = () => {
                        // 图片加载完成后再替换src
                        img.setAttribute('src', src);
                        img.style.opacity = '1';
                    };
                    tempImg.src = src;
                    
                    // 移除data-src属性，防止重复加载
                    img.removeAttribute('data-src');
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '200px 0px', // 提前200px开始加载
            threshold: 0.01
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    };
    
    // 3. 优化首屏图片加载（Banner背景图片）
    const optimizeCriticalImages = () => {
        // 为Banner背景图片添加预加载
        const bannerImages = [
            'https://picsum.photos/1920/1080?random=100',
            'https://picsum.photos/1920/1080?random=101',
            'https://picsum.photos/1920/1080?random=102'
        ];
        
        // 使用Image对象预加载首屏图片
        bannerImages.forEach(src => {
            const img = new Image();
            img.src = src;
        });
        
        // 为Logo添加no-lazy类，确保立即加载
        const logo = document.querySelector('.navbar-brand img');
        if (logo) logo.classList.add('no-lazy');
    };
    
    // 添加懒加载图片的基础样式
    const addLazyLoadStyles = () => {
        const style = document.createElement('style');
        style.textContent = `
            .lazy-image {
                opacity: 0;
                transition: opacity 0.5s ease-in-out;
                background-color: #f5f5f5;
                min-height: 50px;
            }
        `;
        document.head.appendChild(style);
    };
    
    // 初始化图片优化
    addLazyLoadStyles();
    optimizeCriticalImages(); // 先优化关键图片
    convertToLazyLoad(); // 然后将其他图片转为懒加载
    lazyLoadImages(); // 启动懒加载观察器
});

// 添加CSS样式用于按钮波纹效果
const style = document.createElement('style');
style.textContent = `
.ripple {
    position: absolute;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.5);
    transform: scale(0);
    animation: ripple 0.6s linear;
    pointer-events: none;
}

@keyframes ripple {
    to {
        transform: scale(4);
        opacity: 0;
    }
}
`;
document.head.appendChild(style);